// ==== 待办 + 签到 + 数据统计 + 固定提醒面板 ====
let checkinData = {
    lastCheckinDate: null,
    streakDays: 0,
    isCheckedInToday: false
};
let reminderInterval = null; // 提醒定时器
let isReminderPaused = false; // 提醒是否暂停

// 初始化待办模块
function initTodo() {
    const input = document.getElementById('todo-input');
    const addBtn = document.getElementById('todo-add-btn');
    const list = document.getElementById('todo-list');
    const checkinBtn = document.getElementById('todo-checkin');

    // 创建签到按钮（如果没有）
    if (!checkinBtn) {
        const container = document.querySelector('.todo-container');
        const btn = document.createElement('button');
        btn.id = 'todo-checkin';
        container.insertBefore(btn, list);
    }

    // 创建提醒控制按钮（暂停/恢复）
    createReminderControlBtn();

    // 绑定待办事件
    addBtn.onclick = () => addTodo(input, list);
    input.onkeydown = e => {
        if (e.key === 'Enter') addTodo(input, list);
    };

    // 绑定签到事件
    document.getElementById('todo-checkin').onclick = handleCheckin;

    // 加载待办 + 初始化签到
    loadTodos(list);
    initCheckin();

    // 初始化当天数据 + 启动提醒
    saveDailyStats();
    startReminder();

    // 关闭提醒面板按钮事件
    document.getElementById('reminder-close').onclick = function() {
        document.getElementById('reminder-panel').style.display = 'none';
    };
}

// ==== 签到相关 ====
function initCheckin() {
    const checkinBtn = document.getElementById('todo-checkin');
    if (!checkinBtn) return;

    const saved = localStorage.getItem('checkinData');
    if (saved) {
        checkinData = JSON.parse(saved);
    }

    const today = new Date().toDateString();
    checkinData.isCheckedInToday = checkinData.lastCheckinDate === today;
    updateCheckinUI();
}

function updateCheckinUI() {
    const checkinBtn = document.getElementById('todo-checkin');
    if (!checkinBtn) return;

    if (checkinData.isCheckedInToday) {
        checkinBtn.textContent = '今日已签到';
        checkinBtn.disabled = true;
        checkinBtn.style.backgroundColor = '#95a5a6';
    } else {
        checkinBtn.textContent = '每日签到';
        checkinBtn.disabled = false;
        checkinBtn.style.backgroundColor = '#3498db';
    }
}

function handleCheckin() {
    const today = new Date().toDateString();
    if (checkinData.isCheckedInToday) {
        alert('今天已经签过到啦！');
        return;
    }

    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    if (checkinData.lastCheckinDate === yesterday.toDateString()) {
        checkinData.streakDays++;
    } else {
        checkinData.streakDays = 1;
    }

    checkinData.lastCheckinDate = today;
    checkinData.isCheckedInToday = true;
    localStorage.setItem('checkinData', JSON.stringify(checkinData));

    updateCheckinUI();
    saveDailyStats();
    updateStatsData();
    alert(`签到成功！当前连续签到 ${checkinData.streakDays} 天`);
}

// ==== 待办相关 ====
function addTodo(input, todoList) {
    const text = input.value.trim();
    if (!text) return;

    const li = document.createElement('li');
    li.innerHTML = `
        <span>${text}</span>
        <div>
            <button class="todo-complete">完成</button>
            <button class="todo-delete">删除</button>
        </div>
    `;

    li.querySelector('.todo-complete').onclick = () => {
        li.classList.add('completed');
        li.querySelector('.todo-complete').disabled = true;
        li.querySelector('.todo-complete').style.backgroundColor = '#95a5a6';
        saveTodos(todoList);
        saveDailyStats();
        updateStatsData();
        updateReminderPanel(); // 完成后更新提醒面板
    };

    li.querySelector('.todo-delete').onclick = () => {
        const wasCompleted = li.classList.contains('completed');
        li.remove();
        saveTodos(todoList);
        if (wasCompleted) {
            saveDailyStats();
            updateStatsData();
        }
        updateReminderPanel(); // 删除后更新提醒面板
    };

    todoList.appendChild(li);
    input.value = '';
    saveTodos(todoList);
    saveDailyStats();
    updateReminderPanel(); // 新增后更新提醒面板
}

function loadTodos(todoList) {
    const todos = JSON.parse(localStorage.getItem('todos') || '[]');
    const completedStatus = JSON.parse(localStorage.getItem('completedStatus') || '[]');

    todoList.innerHTML = '';
    todos.forEach((todo, index) => {
        const li = document.createElement('li');
        if (completedStatus[index]) li.classList.add('completed');

        li.innerHTML = `
            <span>${todo}</span>
            <div>
                <button class="todo-complete" ${completedStatus[index] ? 'disabled' : ''} 
                    style="${completedStatus[index] ? 'background-color: #95a5a6;' : ''}">完成</button>
                <button class="todo-delete">删除</button>
            </div>
        `;

        li.querySelector('.todo-complete').onclick = () => {
            li.classList.add('completed');
            li.querySelector('.todo-complete').disabled = true;
            li.querySelector('.todo-complete').style.backgroundColor = '#95a5a6';
            const status = JSON.parse(localStorage.getItem('completedStatus') || '[]');
            status[index] = true;
            localStorage.setItem('completedStatus', JSON.stringify(status));
            saveDailyStats();
            updateStatsData();
            updateReminderPanel();
        };

        li.querySelector('.todo-delete').onclick = () => {
            const wasCompleted = li.classList.contains('completed');
            li.remove();
            saveTodos(todoList);
            if (wasCompleted) {
                saveDailyStats();
                updateStatsData();
            }
            updateReminderPanel();
        };

        todoList.appendChild(li);
    });
}

function saveTodos(todoList) {
    const todos = Array.from(todoList.querySelectorAll('li span')).map(span => span.textContent);
    const completedStatus = Array.from(todoList.querySelectorAll('li')).map(li => li.classList.contains('completed'));
    localStorage.setItem('todos', JSON.stringify(todos));
    localStorage.setItem('completedStatus', JSON.stringify(completedStatus));
}

// ==== 每日数据保存 ====
function saveDailyStats() {
    const today = new Date().toISOString().split('T')[0];
    const todoList = document.getElementById('todo-list');
    const totalTodos = todoList ? todoList.children.length : 0;
    const completedTodos = todoList ? todoList.querySelectorAll('li.completed').length : 0;

    let dailyStats = JSON.parse(localStorage.getItem('dailyStats') || '[]');
    const todayIndex = dailyStats.findIndex(item => item.date === today);

    if (todayIndex !== -1) {
        dailyStats[todayIndex] = {
            date: today,
            totalTodos,
            completedTodos,
            checkedIn: checkinData.isCheckedInToday
        };
    } else {
        dailyStats.push({
            date: today,
            totalTodos,
            completedTodos,
            checkedIn: checkinData.isCheckedInToday
        });
    }

    if (dailyStats.length > 30) dailyStats = dailyStats.slice(-30);
    localStorage.setItem('dailyStats', JSON.stringify(dailyStats));
}

// ==== 提醒面板功能 ====
function createReminderControlBtn() {
    const container = document.querySelector('.todo-container');
    if (document.getElementById('reminder-control')) return;

    const btn = document.createElement('button');
    btn.id = 'reminder-control';
    btn.textContent = '暂停提醒';
    btn.style.backgroundColor = '#f39c12';
    btn.style.marginLeft = '12px';

    btn.onclick = () => {
        isReminderPaused = !isReminderPaused;
        btn.textContent = isReminderPaused ? '恢复提醒' : '暂停提醒';
        btn.style.backgroundColor = isReminderPaused ? '#27ae60' : '#f39c12';

        if (!isReminderPaused) {
            updateReminderPanel();
        } else {
            document.getElementById('reminder-panel').style.display = 'none';
        }
    };

    const addBtn = document.getElementById('todo-add-btn');
    container.insertBefore(btn, addBtn.nextSibling);
}

function startReminder() {
    if (reminderInterval) clearInterval(reminderInterval);

    updateReminderPanel(); // 立即检查一次

    // 每小时检查一次
    reminderInterval = setInterval(() => {
        if (!isReminderPaused) {
            updateReminderPanel();
        }
    }, 3600000); // 3600000ms = 1小时
}

function updateReminderPanel() {
    const list = document.getElementById('todo-list');
    const panel = document.getElementById('reminder-panel');
    const reminderList = document.getElementById('reminder-list');

    if (!list || !panel || !reminderList) return;

    const unfinishedItems = list.querySelectorAll('li:not(.completed)');

    if (unfinishedItems.length > 0) {
        panel.style.display = 'block';
        reminderList.innerHTML = '';

        unfinishedItems.forEach(item => {
            const text = item.querySelector('span').textContent;
            const p = document.createElement('p');
            p.textContent = text;
            reminderList.appendChild(p);
        });
    } else {
        panel.style.display = 'none';
    }
}

// 页面关闭时清除定时器
window.addEventListener('beforeunload', () => {
    if (reminderInterval) clearInterval(reminderInterval);
});